define(['app', 'pagination', 'datetime', 'autocomplete', 'editor', 'filesaver', 'fileupload'], function(app) {
    'use strict';
    app.controller('ProductPackage', function($scope, dataFactoryCRM, $q, Upload, $http, $rootScope, $routeParams) {
        $scope.productPackagePage = { pageAll: 1, pageNow: 1, pageSize: $scope.psize, k: 3 };    //分页参数
        $scope.search_param = { name: '', product_line: "", product_id: ""};   //页面搜索参数
        $scope.productPackageList;
        $scope.productLineList = [{}];
        $scope.productList = [{}];
        $scope.productWithLine = [{}];
        $scope.qyServiceList = [{}];    //企业号中服务列表
        $scope.add = {};
        /**获取所有产品线数据**/
        $scope.getProductLineDate = function(){
            dataFactoryCRM.getDataByAPI('ProductPackage/getProductLine').then(function(returnDate) {
                if(returnDate.rcode){
                    $scope.productLineList = returnDate.data;
                }else{
                    $scope.productLineList = [{}];
                }
            });
        }

        /*产品线、产品联动查询*/
        $("#lineSelect").change(function(){
            var selLineCode = $("#lineSelect").val();
            $scope.search_param.product_id = -1;
            dataFactoryCRM.getDataByAPI('ProductPackage/getProduct?product_line_code='+selLineCode)
                .then(function(returnDate) {
                    if(returnDate.rcode)
                        $scope.productList = returnDate.data;
            });
        });
        
        /*根据产品id获取对应产品线*/
        $scope.getProductLineCode = function(product_id){
            dataFactoryCRM.getDataByAPI('ProductPackage/getLineCode?product_id='+product_id).then(function(returnDate) {
                if(returnDate.rcode)
                    $scope.search_param.product_line = returnDate.data;
                $scope.getProductPackageList();
            });
        }

        /**获取产品数据**/
        $scope.getProductDate = function(){
            dataFactoryCRM.getDataByAPI('ProductPackage/getProduct?product_line_code=-1').then(function(returnDate) {
                if(returnDate.rcode){
                    $scope.productList = returnDate.data;
                    $scope.productWithLine = returnDate.productWithLine;    //select中name为“产品名-产品线”
                }else{
                    $scope.productList = [{}];
                    $scope.productWithLine = [{}];
                }
                //获取url判断产品跳转到套餐
                if($routeParams.product_id){
                    $scope.search_param.product_id = $routeParams.product_id;
                    $scope.getProductLineCode($routeParams.product_id);
                }else{
                    $scope.search_param.product_id = -1;
                    $scope.search_param.product_line = -1;
                }
                $scope.getProductPackageList();
            });
        }
        
        /**获取列表页 */
        $scope.getProductPackageList = function() {
            var listParam = $scope.search_param;
            listParam['psize'] = $scope.productPackagePage.pageSize;
            listParam['p'] = $scope.productPackagePage.pageNow;
            var search_url = 'ProductPackage/index?' + $.param(listParam);
            dataFactoryCRM.getDataByAPI(search_url).then(function(returnDate) {
                $scope.rcode = returnDate.rcode;
                $scope.productPackagePage.pageSize = returnDate.psize;
                $scope.productPackagePage.pageAll = returnDate.pall;
                $scope.productPackagePage.pageNow = returnDate.p;
                $scope.productPackageList = returnDate.data;
            });
        };

        /**搜索事件**/
        $scope.search = function() {
            $scope.getProductPackageList();
        }

        //特殊处理semantic dropdown的反向绑定缺陷
        $scope.$watch('search_param.product_line', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='search_param.product_line']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('search_param.product_id', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='search_param.product_id']").dropdown('set selected', newValue);
            });
        }, true);

        /*查看相关订户*/
        $scope.viewOrderCustomer = function(package_code){
            $rootScope.go('/ordercustomer/'+package_code);
        };

        /*添加-监听产品名*/
        $scope.$watch('add_name', function(newvalue, oldvalue) {
            var product_id = $("#product_id").val();
            if (newvalue != oldvalue) {
                $scope.checkNameExist(product_id);
            } 
        });

        /*添加-判断同一产品下，套餐名是否重名*/
        $scope.checkNameExist = function(product_id){
            dataFactoryCRM.postDataByAPI('ProductPackage/checkNameExist','product_id='+product_id+'&name=' +encodeURIComponent($scope.add_name))
                .then(function(d) {
                    if (d.rcode) { //已存在，不能添加
                        $("#checkExist").val('exist');
                        return false;
                    } else {
                        $("#checkExist").val('noexist');
                    }
                });
        }

        /*成功弹窗弹出事件*/
        $scope.successFun = function(){
            setTimeout(function() {
                $('.ui.modal.OK').modal('show');
                setTimeout(function() {
                    $('.ui.modal.OK').modal('hide')
                }, 3000)
            }, 1000);
        }
        /*失败弹窗弹出事件*/
        $scope.failFun = function(){
            $(".ui.modal.Fail").modal('show');
            setTimeout(function() {
                $('.ui.modal.Fail').modal('hide')
            }, 3000);
        }
        /*添加-检查套餐code是否重复*/
        $scope.checkCode = function(){
            var name = $('.frm.add input[name="add_name"]').val();
            dataFactoryCRM.postDataByAPI('ProductPackage/checkCodeExist','package_name=' +encodeURIComponent(name))
                .then(function(d) {
                    if (d.rcode) { //code已存在，不能添加
                        $("#checkCode").val('exist');
                        return false;
                    } else {
                        $("#checkCode").val('noexist');
                    }
                });
        }

        /*获取企业号服务信息*/
        $scope.getQyService = function(){
            dataFactoryCRM.getDataByAPI('ProductPackage/getQyService')
                .then(function(d) {
                    if(d.rcode){
                        $scope.qyServiceList = d.data;
                    }else{
                        $scope.qyServiceList = [{}];
                    }
                });
        }

        /*检查套餐报价格式：多个加个；间隔*/
        $scope.$watch('add_package_price', function(newvalue, oldvalue) {
            if (newvalue != oldvalue) {
                $scope.checkPrice(newvalue);
            } 
        });
        $scope.$watch('edit_package_price', function(newvalue, oldvalue) {
            if (newvalue != oldvalue) {
                $scope.checkPrice(newvalue);
            } 
        });
        $scope.checkPrice = function(values){
            if(values){
                for (var i = values.length - 1; i >= 0; i--) {
                    if(!isNaN(values[i])||values[i]=='.'||values[i]==';'||values[i]=='；'){
                        $("#checkPriceAdd").val('ok');
                        if($("#update_package_code").val)
                            $("#checkPriceEdit").val('ok');
                    }else{
                        $("#checkPriceAdd").val('no');
                        if($("#update_package_code").val)
                            $("#checkPriceEdit").val('no');
                        return false;
                    }
                };
            }
        }
        /*添加套餐页面*/
        $scope.showAddPackage = function(){
            $(".frm.add").form('reset');
            $scope.getQyService();  //获取企业号服务信息
            $('.add_package.modal').modal({
                observeChanges: true,
                onApprove: function() {
                    if ($('.frm.add').form('is valid')&& 'exist' != $("#checkCode").val()) {
                        $scope.addPackage($('.frm.add').serialize()+"&addService="+$("#addService").val());
                    } else   return false;
                }
            }).modal('show');
        }
        /*添加套餐功能*/
        $scope.addPackage = function(addDate){
            dataFactoryCRM.postDataByAPI('ProductPackage/addpackage', addDate)
                .then(function(data) {
                    if (data.rcode) {
                        $scope.msg = '添加套餐成功';
                        $scope.successFun();
                        $scope.getProductPackageList();
                        return true;
                    } else {
                        $scope.msg = data.msg;
                        $scope.failFun();
                        return false;
                    }
                });
        }

        /*编辑-检查套餐名是否重复*/
        $scope.checkEdit = function(){
            var edit_product_id = $("#edit_product_id").val();
            if(edit_product_id){
                $scope.checkNameExistEdit(edit_product_id);
            }
        }
        /*编辑-监听套餐名*/
        $scope.$watch('edit_name', function(newvalue, oldvalue) {
            var edit_product_id = $("#edit_product_id").val();
            if (newvalue != oldvalue ) {
                $scope.checkNameExistEdit(edit_product_id);
            } 
        });
        /*编辑-判断同一产品下，套餐名是否重名*/
        $scope.checkNameExistEdit = function(product_idEdit){
            var checkUrl = 'name=' +encodeURIComponent($scope.edit_name)+'&product_id='+product_idEdit;
            checkUrl = checkUrl + '&package_code='+$("#update_package_code").val();
            dataFactoryCRM.postDataByAPI('ProductPackage/checkNameExist',checkUrl)
                .then(function(d) {
                    if (d.rcode) { //已存在，不能添加
                        $("#checkExistEdit").val('exist');
                        return false;
                    } else {
                        $("#checkExistEdit").val('noexist');
                    }
                });
        }

        /*编辑套餐界面*/
        $scope.showEditPackage = function(){
            $(".frm.edit").form('reset');
            var _vpackage = this.vpackage;
            setTimeout(function() {
                $("#edit_productDiv").dropdown('set selected', _vpackage.product_id);
            }, 300)
            $("#update_package_code").val(_vpackage.package_code);
            $('.frm.edit input[name="edit_name"]').val(_vpackage.name);
            $('.frm.edit input[name="edit_package_service"]').val(_vpackage.package_service);
            $('.frm.edit input[name="edit_package_price"]').val(_vpackage.package_multi_prices);
            $('.frm.edit textarea[name="package_remark"]').val(_vpackage.package_remark);
            $scope.package_code = _vpackage.package_code;
            //编辑套餐，不能更改产品线
            dataFactoryCRM.getDataByAPI('ProductPackage/getProduct?product_line_code='+_vpackage.product_line_code)
                .then(function(returnDate){
                    if(returnDate.rcode){
                        $scope.productWithLine_edit = returnDate.productWithLine;
                    }
            });
            //获取该套餐对应的服务
            dataFactoryCRM.getDataByAPI('ProductPackage/getServOf?package_code='+_vpackage.package_code)
                .then(function(returnDate){
                    $scope.qyServiceList = returnDate.qyServiceList;
                    if(returnDate.selected_service){
                       $scope.selected_service = returnDate.selected_service;
                       setTimeout(function() {
                            angular.element("#selected_service").dropdown('set selected', $scope.selected_service);

                        });
                    }
            });
            $('.ui.edit_package').modal({
                onApprove: function() {
                    if ($('.frm.edit').form('is valid')) {
                        $scope.editPackage($('.frm.edit').serialize()+"&selected_service="+$("#selected_service").val());
                    } else {
                        return false;
                    }
                }
            }).modal('show');
        }
        /*编辑套餐功能*/
        $scope.editPackage = function(editDate){
            dataFactoryCRM.postDataByAPI('ProductPackage/editPackage', editDate)
                .then(function(data) {
                    if (data.rcode && data.rcode==1 || data.rcode==2) {
                        $scope.msg = '更新套餐成功';
                        $scope.successFun();
                        $scope.getProductPackageList();
                        return true;
                    } else if(!data.rcode){
                        $scope.msg = data.msg;
                        $scope.failFun();
                        return false;
                    }
                });
        }

        /*删除套餐*/
        $scope.delPackage = function(){
            var _vpackage = this.vpackage;
            $('.del.modal').modal({
                onApprove: function() {
                    var delUrl = 'ProductPackage/delPackage?package_code=' + _vpackage.package_code;
                    delUrl = delUrl+'&qy_deparment_id='+_vpackage.qy_deparment_id;
                    dataFactoryCRM.getDataByAPI(delUrl)
                        .then(function(data) {
                            console.log(data);
                            if (data.rcode == 1) {
                                $scope.msg = '套餐删除成功';
                                $scope.successFun();
                                if ($scope.productPackageList) {
                                    var i = 0;
                                    for (; i < $scope.productPackageList.length; i++) {
                                        if ($scope.productPackageList[i].package_code == _vpackage.package_code) {
                                            $scope.productPackageList.splice(i, 1);
                                            break;
                                        }
                                    }
                                }
                            } else {
                                $scope.msg = data.msg;
                                $scope.failFun();
                                return false;
                            }
                        });
                    return true;
                }
            }).modal('show');
        }


        //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
        window.loadClientCacheToScope($scope, function(){
            $scope.getProductLineDate();
            $scope.getProductDate();
        });

    });
})